package com.leetcode.array;

import java.util.HashMap;
import java.util.Map;

/**
 * 535. TinyURL 的加密与解密     这是我看过最垃圾的题目
 *  参考地址 http://cn.soulmachine.me/2017-04-10-how-to-design-tinyurl/
 * @ClassName TinyURL
 * @Description 我是一个注释
 * @Author HaiziGe
 * @Date 2018/10/30 9:38
 * @Version 1.0
 **/
public class TinyURL {
    //用于存储长链接-短链接映射
    private static Map<String, String> longShort = new HashMap<>();
    //用于存储短链接-长链接映射
    private static Map<String, String> shortLong = new HashMap<>();
    private static String HOST = "www.tinyUrl.com/";

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        //如果映射中存在key则直接返回
        if (longShort.containsKey(longUrl)) {
            return HOST + longShort.get(longUrl);
        }
        //构造短链
        String shortUrl;
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        //碰撞直到没有重复
        do {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                int n = (int) (Math.random() * chars.length());
                sb.append(chars.charAt(n));
            }
            shortUrl = sb.toString();
        } while (shortLong.containsKey(shortUrl));

        //存储并返回
        shortLong.put(shortUrl, longUrl);
        longShort.put(longUrl, shortUrl);
        return HOST + shortUrl;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return shortLong.get(shortUrl.replace(HOST, ""));
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));